package edu.mit.csail.relo.jdt.util;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;

import edu.mit.csail.relo.jdt.ReloJDTPlugin;

public class UIUtils {
	
    static final Logger logger = ReloJDTPlugin.getLogger(JDTUISupport.class);

    public static URL[] getProjectClasspath(IJavaProject jp) {
		String defaultRoot = jp.getProject().getWorkspace().getRoot().getRawLocation().toOSString();

		try {
			IClasspathEntry[] icpes = jp.getResolvedClasspath(false);
			List<URL> list = new ArrayList<URL>(icpes.length + 1);
			
			// we are only supporting the default output location, there can be
			// more, but we don't know how to get them
            IPath projLocation = jp.getProject().getLocation();
            IPath outputLocation = jp.getOutputLocation();
            IPath relOutputLocation = outputLocation.removeFirstSegments(1); // bec. both have the project name in it
			list.add(projLocation.append(relOutputLocation).toFile().toURL());

			for (IClasspathEntry entry : icpes) {
				if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
					String path = entry.getPath().toOSString();

					if (!(entry.getPath().toFile().exists())) {
						//Check if entry is located in the default workspace root
						File file1 = new File(defaultRoot + path);
						//Check if entry is located in the project's folder or one of its subfolders
						File file2 = new File(projLocation.removeLastSegments(1).removeTrailingSeparator() + path);
						if (file1.exists()) {
							path = defaultRoot + path;
						} else if(file2.exists()) {
							path = projLocation.removeLastSegments(1).removeTrailingSeparator() + path;
						} else {
							continue;
						}
					}

					list.add(new URL("file:///" + path));
				}
			}
			return list.toArray(new URL[list.size()]);
		} catch (JavaModelException e) {
			logger.error("Unexpected Exception", e);
		} catch (MalformedURLException e) {
			logger.error("Unexpected Exception", e);
		}

		return new URL[0];
	}
}
